package com.richest.api.utils;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 统一下单接口请求类
 * 
 * @author 赵鸿超 2017年9月24日
 *
 */
public class GetWxOrderNoUtil {
	private static Logger logger = LoggerFactory.getLogger(GetWxOrderNoUtil.class);
	public final static String RETURN_SUCCESS = "SUCCESS"; // 返回成功标志
	public final static String RETURN_FAIL = "FAIL"; // 返回失败标志

	/**
	 * 发送请求
	 * 
	 * @author 赵鸿超 2017年9月24日
	 * @param strXmlParam
	 *            XML格式的入参
	 * @return String 预支付交易会话标识
	 * @throws Exception
	 */
	public static String sendReq(String strXmlParam) throws Exception {
		CloseableHttpResponse response = null;
		HttpPost httpost = null;
		try {
			CloseableHttpClient httpclient = SSLClientTool.getSSLConnection();

			String strCreateOrderUrl = WXAppInfo.getCreateOrgerUrl();

			httpost = new HttpPost(strCreateOrderUrl);

			httpost.setEntity(new StringEntity(strXmlParam, "UTF-8"));
			response = httpclient.execute(httpost);

			int httpStatus = response.getStatusLine().getStatusCode();
			if (httpStatus >= 200 && httpStatus < 300) {
				String strXmlRep = EntityUtils.toString(response.getEntity(), "UTF-8"); // 响应结果
				logger.debug("response result = " + strXmlRep);

				Map mapResponse = XMLUtil.doXMLParse(strXmlRep);
				String strReturnCode = (String) mapResponse.get("return_code"); // 返回状态码

				if (RETURN_SUCCESS.equals(strReturnCode)) {
					String strResultCode = (String) mapResponse.get("result_code"); // 业务结果
					if (RETURN_SUCCESS.equals(strResultCode)) {
						String strPrepayId = (String) mapResponse.get("prepay_id"); // 预支付交易会话标识
						return strPrepayId;
					} else {
						String strErrCode = (String) mapResponse.get("err_code"); // 错误代码
						String strErrCodeDes = (String) mapResponse.get("err_code_des"); // 错误代码描述
						logger.error("请求微信统一下单接口交易失败,错误代码：" + strErrCode + "，错误描述：" + strErrCodeDes);
						throw new Exception("请求微信统一下单接口交易失败,错误代码：" + strErrCode + "，错误描述：" + strErrCodeDes);
					}
				} else {
					String strReturnMsg = (String) mapResponse.get("return_msg");
					logger.error("请求微信统一下单接口通信失败，原因：" + strReturnMsg);
					throw new Exception("请求微信统一下单接口通信失败，原因：" + strReturnMsg);
				}
			} else {
				HttpEntity entity = response.getEntity();
				httpost.abort();
				logger.error("接收微信接口响应：status=" + httpStatus + " resopnse=" + EntityUtils.toString(entity, "utf-8"));
				throw new Exception(
						"接收微信接口响应：status=" + httpStatus + " resopnse=" + EntityUtils.toString(entity, "utf-8"));
			}
		} catch (Exception ex) {
			throw ex;
		} finally {
			if (response != null) {
				response.close();
			}
			if (httpost != null) {
				httpost.releaseConnection();
			}
		}
	}

}